﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

namespace Trade.DBUtility.DataTableName
{
    public class SerializerAndDeserialize
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] Serializer(object obj)
        {
            byte[] byteReturn;
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            if (obj is System.Data.DataSet)
                ((System.Data.DataSet)obj).RemotingFormat = System.Data.SerializationFormat.Xml;
            else if (obj is System.Data.DataTable)
                ((System.Data.DataTable)obj).RemotingFormat = System.Data.SerializationFormat.Xml;
            formatter.Serialize(stream, obj);
            byteReturn = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(byteReturn, 0, byteReturn.Length);
            stream.Close();
            stream.Dispose();
            return byteReturn;
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static object Deserialize(byte[] bytes)
        {
            object objReturn;
            Stream stream = new MemoryStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            objReturn = formatter.Deserialize(stream);
            stream.Close();
            stream.Dispose();
            return objReturn;

        }
    }
}
